package com.clouduserservice8001.controller;

import com.clouduserservice8001.common.Result;
import com.clouduserservice8001.entity.User;
import com.clouduserservice8001.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody LoginRequest request) {
        try {
            System.out.println("用户服务8002 - 接收到登录请求: " + request);

            if (request.getUserId() == null || request.getPassword() == null) {
                System.out.println("用户服务8002 - 参数验证失败: userId或password为空");
                return Result.error("用户ID和密码不能为空");
            }

            User user = userService.login(request.getUserId(), request.getPassword());
            if (user != null) {
                System.out.println("用户服务8002 - 登录成功: " + user.getUserId());
                return Result.success("登录成功", user);
            } else {
                System.out.println("用户服务8002 - 登录失败: 用户ID或密码错误");
                return Result.error("用户ID或密码错误");
            }
        } catch (Exception e) {
            System.err.println("用户服务8002 - 登录异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("登录服务异常: " + e.getMessage());
        }
    }
    
    /**
     * 创建用户
     */
    @PostMapping
    public Result<Void> createUser(@RequestBody User user, @RequestParam("createBy") String createBy) {
        if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
            return Result.error("用户ID不能为空");
        }
        
        if (userService.isUserIdExists(user.getUserId())) {
            return Result.error("用户ID已存在");
        }
        
        boolean success = userService.createUser(user, createBy);
        if (success) {
            return Result.<Void>success("用户创建成功", null);
        } else {
            return Result.error("用户创建失败");
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public Result<Void> updateUser(@PathVariable("userId") String userId, @RequestBody User user, @RequestParam("updateBy") String updateBy) {
        user.setUserId(userId);
        boolean success = userService.updateUser(user, updateBy);
        if (success) {
            return Result.<Void>success("用户信息更新成功", null);
        } else {
            return Result.error("用户信息更新失败");
        }
    }
    
    /**
     * 删除用户（逻辑删除）
     */
    @DeleteMapping("/{userId}")
    public Result<Void> deleteUser(@PathVariable("userId") String userId, @RequestParam("updateBy") String updateBy) {
        boolean success = userService.deleteUser(userId, updateBy);
        if (success) {
            return Result.<Void>success("用户删除成功", null);
        } else {
            return Result.error("用户删除失败");
        }
    }
    
    /**
     * 启用/禁用用户
     */
    @PutMapping("/{userId}/status")
    public Result<Void> updateUserStatus(@PathVariable("userId") String userId, @RequestParam("status") String status, @RequestParam("updateBy") String updateBy) {
        if (!"0".equals(status) && !"1".equals(status)) {
            return Result.error("状态值无效");
        }
        
        boolean success = userService.updateUserStatus(userId, status, updateBy);
        if (success) {
            String message = "1".equals(status) ? "用户启用成功" : "用户禁用成功";
            return Result.<Void>success(message, null);
        } else {
            return Result.error("用户状态更新失败");
        }
    }
    
    /**
     * 修改密码
     */
    @PutMapping("/{userId}/password")
    public Result<Void> changePassword(@PathVariable("userId") String userId, @RequestBody ChangePasswordRequest request, @RequestParam("updateBy") String updateBy) {
        if (request.getOldPassword() == null || request.getNewPassword() == null) {
            return Result.error("旧密码和新密码不能为空");
        }
        
        boolean success = userService.changePassword(userId, request.getOldPassword(), request.getNewPassword(), updateBy);
        if (success) {
            return Result.<Void>success("密码修改成功", null);
        } else {
            return Result.error("密码修改失败，请检查旧密码是否正确");
        }
    }
    
    /**
     * 重置密码（管理员操作）
     */
    @PutMapping("/{userId}/reset-password")
    public Result<Void> resetPassword(@PathVariable("userId") String userId, @RequestBody ResetPasswordRequest request, @RequestParam("updateBy") String updateBy) {
        if (request.getNewPassword() == null) {
            return Result.error("新密码不能为空");
        }
        
        boolean success = userService.resetPassword(userId, request.getNewPassword(), updateBy);
        if (success) {
            return Result.<Void>success("密码重置成功", null);
        } else {
            return Result.error("密码重置失败");
        }
    }
    
    /**
     * 根据用户ID查询用户
     */
    @GetMapping("/{userId}")
    public Result<User> getUserByUserId(@PathVariable("userId") String userId) {
        User user = userService.getUserByUserId(userId);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("用户不存在");
        }
    }
    
    /**
     * 查询用户列表
     */
    @GetMapping
    public Result<List<User>> getUserList(@RequestParam(value = "userType", required = false) String userType,
                                         @RequestParam(value = "status", required = false) String status,
                                         @RequestParam(value = "keyword", required = false) String keyword) {
        List<User> users = userService.getUserList(userType, status, keyword);
        return Result.success(users);
    }
    
    /**
     * 检查权限
     */
    @GetMapping("/{userId}/permission")
    public Result<Boolean> checkPermission(@PathVariable("userId") String userId, @RequestParam(value = "operation", required = false) String operation) {
        boolean hasPermission = userService.hasPermission(userId, operation);
        return Result.success(hasPermission);
    }
    
    // 内部类：请求对象
    public static class LoginRequest {
        private String userId;
        private String password;
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    public static class ChangePasswordRequest {
        private String oldPassword;
        private String newPassword;
        
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
    
    public static class ResetPasswordRequest {
        private String newPassword;
        
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
}
